package com.guojizhuang.parititioner;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;

import java.io.IOException;
import java.util.Comparator;
import java.util.TreeMap;

public class MonthReducer extends Reducer<Text, Text, Text, LongWritable> {
    TreeMap<Long, String> treeMap;

    @Override
    protected void setup(Reducer<Text, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        treeMap = new TreeMap<>(new Comparator<Long>() {
            @Override
            public int compare(Long o1, Long o2) {
                return (int) (o1-o2);
            }
        });
    }

    @Override
    protected void reduce(Text key, Iterable<Text> values, Reducer<Text, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        long count = 0;
        for (Text value : values)
        {
            count++;
        }
        treeMap.put(count,key.toString());
        if(treeMap.size() >10){
            treeMap.remove(treeMap.firstKey());
        }
    }

    @Override
    protected void cleanup(Reducer<Text, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        for (Long key : treeMap.keySet()){
            // 这样实现的不好处是：reducer的reduce方法会执行多次
            context.write(new Text(treeMap.get(key)), new LongWritable(key));
        }
    }
}
